package com.douxg.fastCoding.web.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.douxg.fastCoding.db.ColumnsEO;
import com.douxg.fastCoding.db.DbFactory;
import com.douxg.fastCoding.db.DbFunction;
import com.douxg.fastCoding.db.DbManager;
import com.douxg.fastCoding.db.mysql.Tables;
import com.douxg.fastCoding.spring.consts.BizCode;
import com.douxg.fastCoding.spring.exception.BizRuntimeException;
import com.douxg.fastCoding.spring.vo.Result;
import com.douxg.fastCoding.web.consts.DbType;
import com.douxg.fastCoding.web.dto.DbInfoDto;
import com.douxg.fastCoding.web.eo.DbInfoEo;
import com.douxg.fastCoding.web.service.DbInfoService;
import com.douxg.fastCoding.web.vo.DbInfoVo;
import com.douxg.fastCoding.web.vo.ElSelectVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Auther douxg
 * @Date 2020/6/13 16:41
 */
@RequestMapping("fc/db")
@RestController
public class DbController {
    @Resource
    private DbInfoService dbInfoService;

    @PostMapping({"testCon", "con"})
    public Result testCon(@RequestBody DbInfoEo dbInfoEo) {
        DbManager.testCon(dbInfoEo);
        return Result.success();
    }

    @PostMapping("getTables")
    public Result getTables(@RequestBody DbInfoDto dbInfoDto, Integer current, Integer size) {
        String name = dbInfoDto.getName();
        if (name == null) {
            throw new BizRuntimeException(BizCode.PARAM_ISNULL);
        }
        DbInfoVo dbInfoVo = dbInfoService.queryOne(dbInfoDto);
        if (dbInfoVo == null) {
            throw new BizRuntimeException(BizCode.DB_NO_DATA);
        }
        Page<Tables> page = DbType.getByName(dbInfoVo.getDbType()).getDbFunction().getTables(current, size, dbInfoVo);
        return Result.success(page);
    }

    @PostMapping("getColumns")
    public Result getColumns(@RequestBody DbInfoEo dbInfoEo, String tableName) {
        DbFunction dbFunction = DbFactory.getDbFunction(dbInfoEo.getDbType());
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<ColumnsEO> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>();
        page.setRecords(dbFunction.getColumnsEo(dbInfoEo, tableName));
        return Result.success(page);
    }

    @GetMapping("dbType")
    public Result dbType() {
        DbType[] values = DbType.values();
        List<ElSelectVo> list = new ArrayList<>();
        for (DbType value : values) {
            if (value.getIsUsable()) {
                String name = value.getName();
                ElSelectVo dicVo = new ElSelectVo();
                dicVo.setLabel(name).setValue(name);
                list.add(dicVo);
            }
        }
        return Result.success(list);
    }
}
